import { ref, computed, reactive } from "vue";
import { defineStore } from "pinia";
import type { ITag } from "@/types/tag-interface";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";

/**
 * 标签页缓存控制
 */
export const useTagStore = defineStore("tag", () => {
  const router = useRouter();
  const maxTagView = ref(15);
  // 初始化首页到路由
  const initPage: ITag = {title: "仪表盘", path: "/", name: "dashboard"};
  // 不参与缓存的路由
  const filterCacheRouters = ["login"];
  // 路由信息 -- 主要存放tag的缓存信息
  const routeCache = ref<ITag[]>([initPage]);
  // 组件缓存信息
  const keepaliveCache = ref<string[]>([initPage.name]);
  // 检查路由是否重复
  const checkTagRepeat = (path: string) => {
    const filter = routeCache.value.filter(x => x.path === path);
    return !!filter.length;
  }
  // 检查缓存是否重复
  const checkCacheRepeat = (name: string) => {
    const filter = keepaliveCache.value.filter(x => x === name);
    return !!filter.length;
  }
  // 添加路由、缓存 返回如为true 表示需要阻止跳转
  const addTagRoute = (tag: ITag) => {
    
    if (checkTagRepeat(tag.path) || checkCacheRepeat(tag.name)) {
      return
    }

    if (routeCache.value.length >= maxTagView.value) {
      message.error("标签页同时最大数量不能超过"+ maxTagView.value +"个");
      return true;
    }

    // 部分页面不参与缓存
    if (filterCacheRouters.includes(tag.name)) {
      return
    }

    routeCache.value.push(tag);
    keepaliveCache.value.push(tag.name);
  }
  // 删除路由、缓存
  const removeTagRoute = (tag: ITag) => {
    if (!checkTagRepeat(tag.path) || !checkCacheRepeat(tag.name)) {
      console.error("与删除的组件不在缓存中");
      return
    }

    const currentIndex = routeCache.value.findIndex(x => x.path === router.currentRoute.value.fullPath);
    const index = routeCache.value.findIndex(x => x.path === tag.path);
    const cacheIndex = keepaliveCache.value.findIndex(x => x === tag.name);

    if (index == -1 || cacheIndex == -1) {
      console.error("与删除的组件不在缓存中!");
      return
    }
    
    const target = routeCache.value[index <= 1 ? 0 : (index - 1)];
    routeCache.value.splice(index, 1);
    keepaliveCache.value.splice(cacheIndex, 1);
    // 关闭的不是当前页面时不需要跳转
    if (index == currentIndex) {
      router.replace(target.path);
    }
  }
  // 清空全部路由
  const clearTagRouteAll = () => {
    routeCache.value = [];
    keepaliveCache.value = [];
  }
  return {
    maxTagView,
    routeCache,
    keepaliveCache,
    checkTagRepeat,
    checkCacheRepeat,
    addTagRoute,
    removeTagRoute,
    clearTagRouteAll
  }
});
